package sk.tuke.constraintbuilder.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

import sk.tuke.constraintbuilder.editor.EditorInput;
import sk.tuke.constraintbuilder.model.RootElement;
import sk.tuke.constraintbuilder.views.ConstraintExplorerView;

public class CloseEditor extends AbstractHandler {
	
	public static final String COMMAND = "sk.tuke.constraintbuilder.command.closeEditor";

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		// Get the view
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		IWorkbenchPage page = window.getActivePage();
		ConstraintExplorerView view = (ConstraintExplorerView) page.findView(ConstraintExplorerView.ID);

		// Get the selection
		ISelection selection = view.getSite().getSelectionProvider().getSelection();
		if (selection != null && selection instanceof IStructuredSelection) {
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			// If we had a selection lets open the editor
			if (obj != null) {
				RootElement element = (RootElement) obj;
				EditorInput input = new EditorInput(element);
				page.closeEditor(page.findEditor(input), false);
			}
		}
		return null;
	}

}